package com.license.logic.implementation;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.license.logic.mappers.UserMapper;
import com.license.logic.pojo.User;

public class UserImplementation {

	private static SqlSessionFactory sf;
	
	private SqlSessionFactory getSqlSessionFactory() throws IOException {
		String resource = "mybatis.config.xml";
		Reader reader = Resources.getResourceAsReader(resource);
		sf = new SqlSessionFactoryBuilder().build(reader);
		return sf;
	} 
	// constructor will receive a myBatis sessionFactory object
	public UserImplementation() {
		
	}
	
	public UserImplementation(SqlSessionFactory containerSessionFactory) throws IOException {
		if (containerSessionFactory == null)
			System.err.println("Error: could not load myBatis sessionFactory");
		sf = getSqlSessionFactory();
	}
	
	public void insertUser(User user) throws IOException {
		
		SqlSession session =getSqlSessionFactory().openSession();
		try {
		
			 session.getMapper(UserMapper.class).insertUser(user);
		
		} finally {
			session.close();
		}
	}
	
	public User selectUser(String userName) throws IOException{
		SqlSession session =getSqlSessionFactory().openSession();
		User user;
		try {
			 user = session.getMapper(UserMapper.class).selectUser(userName);
		
		} finally {
			session.close();
		}
		return user;
	}
	
	public User logIn(String userName, String password) throws IOException {
		
		SqlSession session =getSqlSessionFactory().openSession();
		try {
			User user = session.getMapper(UserMapper.class).login(userName, password);
			return user;
		} finally {
			session.close();
		}
	}
	
	public List<User> getUsers() throws IOException {
		SqlSession session = getSqlSessionFactory().openSession();
		List<User> users = new ArrayList<User>();
		try {
			users = session.getMapper(UserMapper.class).getUsers();
		} finally {
			session.close();
		}
		return users;
	}
	
	public void deleteUser(User user) throws IOException {
		SqlSession session = getSqlSessionFactory().openSession();
		try {
			session.getMapper(UserMapper.class).deleteUser(user);
		} finally {
			session.close();
		}
	}
	
	public void editUser(User user) throws IOException {
		SqlSession session = getSqlSessionFactory().openSession();
		try{
			 session.getMapper(UserMapper.class).editUser(user);
		} finally {
			session.close();
		}
	}
}
